<template>
    <div class="content">
      <div class="content-head">
        <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="reset_btn">重置</el-button>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="add_btn">添加</el-button>
        <el-button type="info" size="mini" icon="el-icon-download" :loading="exportBtnLoading" @click="export_btn">导出</el-button>
        <el-popover placement="right" width="" trigger="click" ref="popover" @show="popoverShowEvent">
          <el-form :model="popoverForm" :rules="popoverFormRules" ref="popoverForm" size="mini" label-width="70px" class="popoverForm">
            <el-form-item label="装配线" prop="salaryA_tmp">
              <el-input v-model="popoverForm.salaryA_tmp" @input="handleSalaryInput($event,'salaryA_tmp')" autocomplete="off" placeholder="请输入单班工资"></el-input>
            </el-form-item>
            <el-form-item label="机加工" prop="salaryB_tmp">
              <el-input v-model="popoverForm.salaryB_tmp" @input="handleSalaryInput($event,'salaryB_tmp')" autocomplete="off" placeholder="请输入单班工资"></el-input>
            </el-form-item>
            <el-form-item label="走心机" prop="salaryC_tmp">
              <el-input v-model="popoverForm.salaryC_tmp" @input="handleSalaryInput($event,'salaryC_tmp')" autocomplete="off" placeholder="请输入单班工资"></el-input>
            </el-form-item>
          </el-form>
          <div style="text-align: right; margin: 10px">
            <el-button type="primary" plain size="mini" @click="popoverClearEvent">清空</el-button>
            <el-button type="primary" size="mini" :loading="popoverConfirmLoading" @click="popoverConfirmEvent">确定</el-button>
          </div>
          <el-button slot="reference" type="primary" plain size="mini" icon="el-icon-edit" style="margin-left:10px;">编辑单班工资</el-button>
        </el-popover>
      </div>
      <div class="content-table">
        <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" class="content-table-item">
            <el-table-column prop="equipment" label="设备名" width="">
              <template slot-scope="scope" slot="header">
                <table-head-filter label="设备名" type="selectAndSearch" :bindData="formData.equipmentName"  filterField="equipmentName" @change="filterChangeEvent" :alternativeOption="associativeSearch.equipmentName"></table-head-filter>
              </template>
            </el-table-column>
            <el-table-column prop="assemblyNumber" label="总成号" width=""></el-table-column>
            <el-table-column prop="productName" label="产品名称" width=""></el-table-column>
            <el-table-column prop="productModel" label="产品型号" width="">
              <template slot-scope="scope" slot="header">
                <table-head-filter label="产品型号" type="selectAndSearch" :bindData="formData.productModel" filterField="productModel" @change="filterChangeEvent" :alternativeOption="associativeSearch.productModel"></table-head-filter>
              </template>
            </el-table-column>
            <el-table-column prop="processStep" label="工序" width=""></el-table-column>
            <el-table-column prop="pieceRate" label="单件节拍" width=""></el-table-column>
            <el-table-column prop="standardManpower" label="标准用人力" width=""></el-table-column>
            <el-table-column prop="operatingTime" label="设备运行时长" width=""></el-table-column>
            <el-table-column prop="createdDate" label="创建时间" width="150"></el-table-column>
            <el-table-column prop="" label="操作" width="180"  fixed="right">
              <template slot-scope="{ row, $index }">
                <el-button type="text" @click="examine_btn(row,$index)">查看</el-button>
                <el-button type="text" @click="edit_btn(row,$index)">编辑</el-button>
                <el-popconfirm title="确定删除吗？" style="margin-left:10px;" @confirm="delete_btn(row,$index)">
                  <el-button type="text" slot="reference">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
        </el-table>
      </div>
      <div class="content-footer">
        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
      <!-- dialog -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="dialogCancel_btn" class="dialog-content">
        <el-form :model="dialogFormData" ref="dialogForm" :rules="dialogFormRules" label-position="left" size="small" :disabled="dialogState === 0" label-width="110px" style="width:90%;">
          <el-form-item prop="equipment" label="设备名">
            <el-input v-model="dialogFormData.equipment" placeholder="请输入设备名"></el-input>
          </el-form-item>
          <el-form-item prop="assemblyNumber" label="总成号">
            <el-input v-model="dialogFormData.assemblyNumber" placeholder="请输入总成号"></el-input>
          </el-form-item>
          <el-form-item prop="productName" label="产品名称">
            <el-input v-model="dialogFormData.productName" placeholder="请输入产品名称"></el-input>
          </el-form-item>
          <el-form-item prop="productModel" label="产品型号">
            <el-input v-model="dialogFormData.productModel" placeholder="请输入产品型号"></el-input>
          </el-form-item>
          <el-form-item prop="processStep" label="工序">
            <el-input v-model="dialogFormData.processStep" placeholder="请输入工序"></el-input>
          </el-form-item>
          <el-form-item prop="pieceRate" label="单件节拍">
            <el-input v-model="dialogFormData.pieceRate" placeholder="请输入单件节拍"></el-input>
          </el-form-item>
          <el-form-item prop="standardManpower" label="标准用人力">
            <el-input v-model="dialogFormData.standardManpower" placeholder="请输入标准用人力"></el-input>
          </el-form-item>
          <el-form-item prop="operatingTime" label="设备运行时长">
            <el-input v-model="dialogFormData.operatingTime" @input="handleFormInput($event,'operatingTime')" placeholder="请输入设备运行时长"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" v-show="dialogState !== 0" class="dialog-footer">
          <el-button size="small" @click="dialogCancel_btn">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm_btn" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>

  <script>
  import { reqMeterList, reqSaveMeter, reqUpdtaeMeter, reqDeleteMeterById, reqMeterExport, reqDefaultSalary, reqUpdateSalary } from "@/api/meterTable.js";
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
  export default {
    name:"meterTable",  //节拍维护小程序
    components:{
      TableHeadFilter
    },
    data() {
      return {
        formData:{
          equipmentName:"",
          productModel:"",
          workshop:"",  //车间
          workshopOptions:['装配线','机加工','走心机']
        },
        dialogFormData:{
          id:"",
          equipment:"",
          assemblyNumber:"",
          productName:"",
          productModel:"",
          processStep:"",
          pieceRate:"",
          standardManpower:"",
          singleShiftWage:"",
          operatingTime:""
        },
        dialogFormRules:{
          equipment: [{ required: true, message: '请输入设备名', trigger: 'change' }],
          assemblyNumber: [{ required: false, message: '请输入总成号', trigger: 'blur' }],
          productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
          productModel: [{ required: true, message: '请输入产品型号', trigger: 'blur' }],
          processStep: [{ required: true, message: '请输入工序', trigger: 'blur' }],
          pieceRate: [{ required: true, message: '请输入单件节拍', trigger: 'blur' }],
          standardManpower: [{ required: true, message: '请输入标准用人力', trigger: 'blur' }],
          singleShiftWage: [{ required: true, message: '请输入单班工资', trigger: 'blur' }],
          operatingTime: [{ required: true, message: '请输入设备运行时长', trigger: 'blur' }]
        },
        tableData:[],
        tableLoading:false,
        tableMaxHeight:450,
        currentPage:1,
        pageSize:10,
        total:0,
        dialogVisible:false,  //dialog弹出层
        dialogState:0,  //dialog弹出层状态 0-查看 1-编辑 2-添加
        exportBtnLoading:false,
        popoverForm:{
          salaryA:"",
          salaryB:"",
          salaryC:"",
          salaryA_tmp:"",
          salaryB_tmp:"",
          salaryC_tmp:""
        },
        popoverFormRules:{
          salaryA_tmp: [{ required: true, message: '请输入装配线单班工资', trigger: 'blur' }],
          salaryB_tmp: [{ required: true, message: '请输入机加工单班工资', trigger: 'blur' }],
          salaryC_tmp: [{ required: true, message: '请输入走心机单班工资', trigger: 'blur' }],
        },
        popoverConfirmLoading:false,
        associativeSearch:{
          equipmentName:null,
          productModel:null
        }
      }
    },
    mounted(){
      this.getMeterList();
      this.getDefaultSalary();
      //精致环境下进行自动旋转
      autoOrientation();
      this.calculateTableMaxHeight();
      document.title = "节拍维护小程序";
      window.addEventListener("resize",this.calculateTableMaxHeight);
      this.dealAssociativeSearch();
    },
    beforeDestroy(){
      window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    computed:{
      dialogTitle(){
        const status = this.dialogState;
        let title = "";
        if(status === 0){
          title = "查看";
        } else if(status === 1){
          title = "编辑";
        } else {
          title = "添加";
        }
        return title;
      }
    },
    methods:{
      //分页获取节拍列表信息
      async getMeterList () {
        this.tableLoading = true;
        const { workshop, equipmentName, productModel } = this.formData;
        const parameters = {page:this.currentPage, size:this.pageSize, workShop:workshop, equipment:equipmentName, productModel };
        reqMeterList(parameters).then(res => {
          if(res.data.code === 200){
            this.tableData = res.data.data.content;
            this.total = res.data.data.totalElements;
          }
          this.tableLoading = false;
          console.log("分页获取节拍列表信息",res);
        }).catch(err => {
          this.$message({type:"error",message:"列表数据获取失败"});
          this.tableLoading = false;
        })
      },
      //查询重置导出按钮
      add_btn(){
        this.dialogState = 2;
        this.dialogVisible = true;
      },
      search_btn(){
        const { workshop, equipmentName, productModel } = this.formData;
        if(workshop === "" && equipmentName === "" && productModel === ""){
          //this.$message({type:"warning",message:"搜索条件为空!"});
          //return;
        }
        this.currentPage = 1;
        this.pageSize = 10;
        this.getMeterList();
      },
      reset_btn(){
        const tmp = this.formData;
        tmp.workshop = "";
        tmp.equipmentName = "";
        tmp.productModel = "";
        this.currentPage = 1;
        this.pageSize = 10;
        this.getMeterList();
      },
      export_btn() {
        const { workshop, materialCode, internalDrawing } = this.formData;
        const parameters = { workShop:workshop, projectNo:materialCode, internalDrawing:internalDrawing };
        this.$confirm('即将导出当前内容,数据将根据筛选条件进行过滤', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
            .then(async () => {
                this.exportBtnLoading = true;
                let res = await reqMeterExport(parameters);
                if (res.status === 200) {
                  let blob = res.data;
                  let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                  const aLink = document.createElement('a');
                  aLink.href = url;
                  let timestamp = new Date().getTime();
                  aLink.setAttribute('download', '节拍报表信息_' + timestamp);
                  document.body.appendChild(aLink);
                  aLink.click();
                  document.body.removeChild(aLink);
                  this.$message.success('导出成功');
                  this.exportBtnLoading = false;
                } else {
                  this.$message.error('导出失败,请重试');
                  this.exportBtnLoading = false;
                }
            }).catch(() => {
                this.$message({type: 'info', message: '已取消导出!'});          
            });
      },
      examine_btn(row,index){
        this.dialogState = 0;
        this.dialogVisible = true;
        const tmp = this.dialogFormData;
        const { id, equipment, assemblyNumber,productName,productModel,processStep,pieceRate,standardManpower, singleShiftWage, operatingTime } = row;
        tmp.id = id;
        tmp.equipment = equipment;
        tmp.assemblyNumber = assemblyNumber;
        tmp.productName = productName;
        tmp.productModel = productModel;
        tmp.processStep = processStep;
        tmp.pieceRate = pieceRate;
        tmp.standardManpower = standardManpower;
        tmp.operatingTime = operatingTime;
      },
      edit_btn(row,index){
        this.examine_btn(row,null);
        this.dialogState = 1;
        this.dialogVisible = true;
      },
      delete_btn(row,index){
        const id = row.id;
        reqDeleteMeterById(id).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"删除成功"});
            this.getMeterList();
          }
          console.log('节拍删除',response);
        }).catch(error => {
          this.$message({type:"error",message:"删除失败"});
          console.log('节拍删除api',error);
        })
      },
      dialogCancel_btn(){
        this.dialogVisible = false;
        this.dialogFormData.id = "";
        this.dialogFormData.equipment = "";
        this.dialogFormData.assemblyNumber = "";
        this.dialogFormData.productName = "";
        this.dialogFormData.productModel = "";
        this.dialogFormData.processStep = "";
        this.dialogFormData.pieceRate = "";
        this.dialogFormData.standardManpower = "";
        this.dialogFormData.operatingTime = "";
        this.$refs.dialogForm.resetFields();
        //console.log('dialog关闭');
      },
      async dialogConfirm_btn(){
        const { id,equipment,assemblyNumber,productName,productModel,processStep,pieceRate,standardManpower, operatingTime } = this.dialogFormData;
        const parameters = {equipment,assemblyNumber,productName,productModel,processStep,pieceRate,standardManpower, operatingTime };
        const dialogState = this.dialogState;
        const dialogFormRef = this.$refs.dialogForm;
        let result = false;
        dialogFormRef.validate((validateResult,obj) => {
            result = validateResult;
        });
        if(!result) return;
        if(dialogState === 1){
          parameters.id = id;
          try {
            const result = await reqUpdtaeMeter(parameters);
            if(result.data.code === 200){
              this.$message({type:"success",message:"更新成功"});
              this.dialogCancel_btn();
              this.getMeterList();
            } else {
              this.$message({type:"error",message:"更新失败"});
            }
            console.log("更新节拍数据api",result); 
          } catch (error) {
            this.$message({type:"error",message:"更新失败，请重试!"});
            console.log('更新节拍数据api',error);
          }
        } else if (dialogState === 2){
          //添加
          try {
            const result = await reqSaveMeter(parameters);
            if(result.data.code === 200){
              this.$message({type:"success",message:"添加成功"});
              this.dialogCancel_btn();
              this.getMeterList();
            } else {
              this.$message({type:"error",message:"添加失败"});
            }
            console.log("添加节拍数据api",result);
          } catch (error) {
            console.log('添加节拍数据api',error);
            this.$message({type:"error",message:error.response.data.message});
          }
        }
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        this.getMeterList();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        this.getMeterList();
      },
      //格式化时间
      formatDate(val,type){
          let date = new Date(val);
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let day = date.getDate();
          let h = date.getHours();
          let m = date.getMinutes();
          let s = date.getSeconds();
          if(type === 0){
              return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
          } else if (type === 1){
              return year + "-" + this.addZero(month) + "-" + this.addZero(day);
          } else if (type === 2){
              return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
          } else if (type === 3){
              return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
          }
      },
      addZero(val){
          return val > 9 ? val : "0" + val;
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".content-table");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 10;
        })
      },
      //tableHeadFiler的change事件
      filterChangeEvent(parameter){
        const { state, filterField, selectedValue } = parameter;
        if(state === 'clear'){
          //清空操作
          if(this.formData[filterField] !== ""){
            this.formData[filterField] = "";
            this.search_btn();
          }
        }
        if(state === 'confirm'){
          //确定操作
          this.formData[filterField] = selectedValue;
          if(selectedValue !== ""){
            this.search_btn();
          }
        }
      },
      handleSalaryInput(event,option) {
        let value = event;
        value = value.replace(/[^0-9.]/g, '');
        value = value.replace(/(\..*)\./g, '$1');
        value = value.replace(/^0+(?!\.)/, '');
        value = value.replace(/^0+(\d)/, '$1');
        value = value.replace(/^(\d+\.\d{2})\d*/, '$1');
        value = value.replace(/^\./, '0.');
        value = value.replace(/^-/, '');
        this.popoverForm[option] = value;
      },
      handleFormInput(event,option) {
        let value = event;
        value = value.replace(/[^0-9.]/g, '');
        value = value.replace(/(\..*)\./g, '$1');
        value = value.replace(/^0+(?!\.)/, '');
        value = value.replace(/^0+(\d)/, '$1');
        value = value.replace(/^(\d+\.\d{2})\d*/, '$1');
        value = value.replace(/^\./, '0.');
        value = value.replace(/^-/, '');
        this.formData[option] = value;
      },
      popoverShowEvent(){
        const { salaryA,salaryB,salaryC } = this.popoverForm;
        this.popoverForm.salaryA_tmp = salaryA;
        this.popoverForm.salaryB_tmp = salaryB;
        this.popoverForm.salaryC_tmp = salaryC;
      },
      popoverClearEvent(){
        this.$refs.popoverForm.resetFields();
      },
      popoverConfirmEvent(){
        let checkResult = false;
        this.$refs.popoverForm.validate(valid => {
          checkResult = valid;
        })
        if(!checkResult){
          return ;
        }
        this.updateSalary();
      },
      getDefaultSalary(){
        reqDefaultSalary().then(response => {
          if(response.data.code === 200){
            const salaryList = response.data.data;
            const popoverForm = this.popoverForm;
            for(let i = 0; i < salaryList.length; i ++){
              const value = salaryList[i];
              if(value.configKey.includes("装配线")){
                popoverForm.salaryA = value.configValue;
              } else if(value.configKey.includes("机加工")){
                popoverForm.salaryB = value.configValue;
              } else if (value.configKey.includes("走心机")){
                popoverForm.salaryC = value.configValue;
              }
            }
          }
          console.log('获取默认单班工资api',response);
        }).catch(error => {
          console.log('获取默认单班工资api',error);
        })
      },
      updateSalary(){
        const popoverForm = this.popoverForm;
        const parameter = [
          { configKey:"装配线", configValue:popoverForm.salaryA_tmp },
          { configKey:"机加工", configValue:popoverForm.salaryB_tmp },
          { configKey:"走心机", configValue:popoverForm.salaryC_tmp }
        ];
        this.popoverConfirmLoading = true;
        reqUpdateSalary(parameter).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"单班工资编辑成功"});
            this.popoverConfirmLoading = false;
            this.getDefaultSalary();
            this.$refs.popover.doClose();
          }
          console.log('更新单班工资api',response);
        }).catch(error => {
          this.$message({type:"error",message:"单班工资更新失败，请重试"});
          this.popoverConfirmLoading = false;
          console.log('更新单班工资api',error);
        })
      },
      //联想搜索解决方案
      dealAssociativeSearch(){
        //请求所有数据,目前数据总条数118,设置size:300
        const equipmentNameSet = new Set();
        const productModelSet = new Set();
        reqMeterList({page:1,size:300}).then(res => {
          if(res.data.code === 200){
            const list = res.data.data.content;
            for(let i = 0; i < list.length; i ++){
              equipmentNameSet.add(list[i].equipment);
              productModelSet.add(list[i].productModel);
            }
            console.log("联想搜索数据",res);
          }
          this.associativeSearch.equipmentName = Array.from(equipmentNameSet);
          this.associativeSearch.productModel = Array.from(productModelSet);
        }).catch(err => {
          console.log("联想搜索",err);
        })
      }
    }
  }
  </script>
  
  <style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 2% 5%;
    box-sizing: border-box;
  
    .content-head{
      flex: 0.5;
    }
    .content-table{
      flex: 8;
      margin: 10px 0;
    }
    .content-footer{
      flex: 0.5;
      display: flex;
      justify-content: flex-end;
    }
  }
  </style>